import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const DEFAULT_IGNORES = ['node_modules', 'dist', '.git', 'test']

/**
 * 打印文件夹结构
 * @param {string} dir - 起始目录
 * @param {object} options - 配置选项
 * @param {string[]} options.ignoreList - 要忽略的文件夹
 */
export function printFolderTree(dir, options = {}, prefix = '') {
  const ignoreList = options.ignoreList || []

  if (!fs.existsSync(dir)) {
    console.error(`❌ 目录不存在: ${dir}`)
    return
  }

  const entries = fs.readdirSync(dir).filter(name => !ignoreList.includes(name))
  const total = entries.length

  entries.forEach((entry, index) => {
    const fullPath = path.join(dir, entry)
    const isLast = index === total - 1
    const connector = isLast ? '└── ' : '├── '
    const newPrefix = prefix + (isLast ? '    ' : '│   ')

    const stat = fs.statSync(fullPath)
    if (stat.isDirectory()) {
      console.log(`${prefix}${connector}${entry}/`)
      printFolderTree(fullPath, options, newPrefix)
    } else {
      console.log(`${prefix}${connector}${entry}`)
    }
  })
}

/**
 * 构建忽略列表
 */
export function getIgnoreList(userIgnore = '', showAll = false) {
  if (showAll) return []
  const userIgnores = userIgnore.split(',').map(s => s.trim()).filter(Boolean)
  return [...new Set([...DEFAULT_IGNORES, ...userIgnores])]
}
